/**
 *
 */
package stephen.data.dict;

import java.io.FileWriter;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;

/**
 * @author Stephen An
 * @date 2019年11月30日 上午12:21:40
 */
public class TableTools {
	public static String jsonData = "D:\\我的文档\\桌面\\DataDict\\data.json";

	public static void main(String[] args) {
		try {
			Map<String, List<List<String>>> tablesMap = generateTablesMap();
			JSON.writeJSONString(new FileWriter(jsonData), tablesMap, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat);

		} catch (IOException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @author Stephen An
	 * @throws SQLException 
	 * @date 2019年11月30日 上午1:56:18
	 */
	public static Map<String, List<List<String>>> generateTablesMap() throws SQLException {
		String currentTable = null;
		Map<String, List<List<String>>> tablesMap = new TreeMap<>();

		String columnsSQL = "SELECT COLS.TABLE_NAME, COLS.COLUMN_NAME, COLS.COLUMN_TYPE " + "FROM INFORMATION_SCHEMA.COLUMNS COLS " + "WHERE COLS.TABLE_SCHEMA = 'bootdo' "
				+ "ORDER BY COLS.TABLE_NAME, COLS.ORDINAL_POSITION";

		List<Entity> results = Db.use().query(columnsSQL);

		for (int i = 0; i < results.size(); i++) {

			Entity entity = results.get(i);
			String table = entity.getStr("TABLE_NAME");
			String column = entity.getStr("COLUMN_NAME");
			String type = entity.getStr("COLUMN_TYPE");

			if (!table.equals(currentTable)) {
				currentTable = table;
				tablesMap.put(currentTable, new ArrayList<List<String>>());
			}
			tablesMap.get(currentTable).add(CollUtil.newArrayList(column, type, "", "Internal", "No"));

		}

		return tablesMap;

	}
}
